/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Facades;

import Entities.Message;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author roycalderon
 */
@Stateless
public class MessageFacade extends AbstractFacade<Message> {

    @PersistenceContext(unitName = "MaRoY-LibraryPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public MessageFacade() {
        super(Message.class);
    }

    /**
     * Obtiene ultimo mensaje
     *
     * @author royCalderon
     */
    public Integer getIdLastMessage() {
        Query q = em.createQuery("SELECT MAX(m.idMessage) FROM Message m");
        try {
            return (Integer) q.getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Obtiene los mensajes del usuario
     *
     * @author royCalderon
     */
    public List<Message> getMessageUser(Integer iduser, Integer idusermessage) {
        Query q = em.createQuery("SELECT um.message FROM UserMessages um "
                + "WHERE (um.UserMessagesPK.userId = :idusermessage "
                + "AND um.message.userid.id= :iduser) or (um.UserMessagesPK.userId = :iduser "
                + "AND um.message.userid.id = :idusermessage) "
                + "ORDER BY um.message.date ASC");
        q.setParameter("idusermessage", iduser);
        q.setParameter("iduser", idusermessage);
        try {
            return (List<Message>) q.getResultList();
        } catch (Exception e) {
            return null;
        }
    }
}
